import { prisma } from '@/lib/prisma/client'
import { NextResponse } from 'next/server'
import { format } from 'date-fns'
import { SceneHistory } from '@prisma/client'

export async function POST(request: Request) {
  try {
    const { sceneIds } = await request.json()

    if (!Array.isArray(sceneIds)) {
      throw new Error('无效的场景ID列表')
    }

    // 获取所有场景信息
    const scenes = await prisma.scene.findMany({
      where: {
        id: {
          in: sceneIds
        }
      }
    })

    // 获取所有历史记录
    const history = await prisma.sceneHistory.findMany({
      where: {
        sceneId: {
          in: sceneIds
        }
      },
      orderBy: [
        { sceneId: 'asc' },
        { startTime: 'desc' }
      ]
    })

    // 生成CSV内容
    const csvHeaders = [
      '场景名称',
      '执行时间',
      '状态',
      '消息',
      '执行时长(ms)',
      '成功动作数',
      '失败动作数',
      '重试次数',
      '原始执行ID'
    ]

    const rows = history.map((record: SceneHistory) => {
      const scene = scenes.find(s => s.id === record.sceneId)
      const actionLogs = record.actionLogs as any[]
      const successCount = actionLogs.filter(log => log.status === 'SUCCESS').length
      const failureCount = actionLogs.filter(log => log.status === 'FAILED').length

      return [
        scene?.name || '',
        format(record.startTime, 'yyyy-MM-dd HH:mm:ss'),
        record.status,
        record.message || '',
        record.duration,
        successCount,
        failureCount,
        record.retryCount,
        record.retryOf || ''
      ]
    })
    
    const csvContent = [
      csvHeaders.join(','),
      ...rows.map(row => row.join(','))
    ].join('\n')

    // 设置响应头
    const headers = new Headers()
    headers.set('Content-Type', 'text/csv; charset=utf-8')
    headers.set(
      'Content-Disposition',
      `attachment; filename="场景执行历史_批量_${format(new Date(), 'yyyyMMdd_HHmmss')}.csv"`
    )

    return new Response('\ufeff' + csvContent, { headers })
  } catch (error) {
    return NextResponse.json(
      { error: '导出历史记录失败' },
      { status: 500 }
    )
  }
} 